﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SPMS.Utility
{
    /// <summary>
    /// 模板匹配辅助类
    /// </summary>
    /// <remarks></remarks>
    /// <history>
    /// [zanezeng]   2008-10-28 13:14    Created
    /// </history>
    public static class PatternUtility
    {
        /// <summary>
        /// 判断指定的字符串是否满足指定的简单模板
        /// </summary>
        /// <param name="pattern">用于匹配的模板</param>
        /// <param name="value">用于匹配的字符串</param>
        /// <param name="ignoreCase">是否忽略字符串的大小写</param>
        /// <returns>
        /// 	<c>true</c>：符合模板<br/>
        /// 	<c>false</c>：不符合模板
        /// </returns>
        /// <remarks>如果模板为NULL或者输入字符串为NULL，那么认为不匹配</remarks>
        /// <history>
        /// [zanezeng]   2008-10-28 13:15    Created
        /// </history>
        public static bool IsSimpleMatch(string pattern, string value, bool ignoreCase)
        {
            //判断是否为NULL
            if (null == pattern || null == value)
            {
                return false;
            }

            //判断字符串是否相等
            if (0 == string.Compare(pattern, value, ignoreCase) || 0 == string.Compare("*", pattern, ignoreCase))
            {
                //如果Pattern为*或者Pattern与用于匹配的字符串相等，则认为匹配
                return true;
            }

            //判断是否为空
            if (string.IsNullOrEmpty(pattern))
            {
                //用于比较的字符串是否为空
                //如果用于比较的字符串也为空，则认为匹配
                return string.IsNullOrEmpty(value);
            }

            //转化Pattern
            //将*替换为[.]*
            pattern = pattern.Replace("*", ".*");

            //转化Pattern
            //将?转化为.
            pattern = pattern.Replace("?", ".");

            //添加开始符号和结束符号
            pattern = string.Format("^{0}$", pattern);

            //匹配条件
            RegexOptions options = RegexOptions.Singleline;

            //判断是否大小写敏感
            if (ignoreCase)
            {
                options |= RegexOptions.IgnoreCase;
            }

            //创建正则表达式
            Regex regex = new Regex(pattern, options);

            //判断是否匹配
            return regex.IsMatch(value);
        }
    }
}
